package com.ansion.commonchat.contact.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.helper.UserHelper;
import com.ansion.basedb.storage.SharedPreferencesManager;
import com.ansion.commonchat.contact.AppConstants;
import com.ansion.log.VLog;
import com.ansion.utils.CocoLocalBroadcastUtil;
import com.ansion.utils.ContactUtil;


/*
 * use for maintab init loading ,loading Finish ,loading retry Dialog
 */
public class SyncDataProgressManager {
    public static final String ACTION_GETMATCHEDUSER_RETRY = "syncdataprogressmanager_action_getmatcheduser_retry";
    public static final String MESSAGE_LOAD_FINISH = "message_load_finish";
    public static final String FAVOURATEFRAGMENT_LOAD_FINISH = "favouratefragment_load_finish";
    public static final String CONTACTFRAGMENT_LOAD_FINISH = "contactfragment_load_finish";
    private static final String MAINTAB_LOAD_PROGRESS = "maintab_load_progress";
    public static final String SYNCDATAPROGRESS_END = "syncdataprogress_end";

    private boolean matchFriendFinish = false;
    private static final int MAX = 100;
    private boolean needShowRetryDialog = false;
    private static final String TAG = "SyncDataProgressManager";
    /**
     * 已加载百分比
     */
    private int m_loadedPercent = 0;

    /**
     * 显示的最大百分比
     */
    private int m_max = MAX;

    /**
     * 断网后重置标志
     */
    private boolean isReset = false;

    static SyncDataProgressManager manager;

    private SyncDataProgressManager() {
        m_loadedPercent = 0;
        m_max = MAX;
        initReceiver();
    }

//	public static SyncDataProgressManager newInstance() {
//		if (!isLoadingSyncDataFinish() && null == manager) {
//			manager = new SyncDataProgressManager();
//		}
//		return manager;
//	}

    public static SyncDataProgressManager getInstance() {
        synchronized (SyncDataProgressManager.class) {
            if (manager == null) {
                manager = new SyncDataProgressManager();
            }
        }
        return manager;

    }

    public void clearPercent() {
        synchronized (this) {
            m_loadedPercent = 0;
            m_max = MAX;
            isReset = true;
            needShowRetryDialog = false;
        }
    }

    public void addLoadedTaskCount() {
        // if (!HelperFunc.hasInternet()) {
        // return;
        // }
        synchronized (this) {
            // m_max += 20;
            // if (m_max > 100) {
            // m_max = 101;
            // setLoadingSyncDataFinish();
            // }
            // if (m_loadedPercent == 0) {
            // m_loadedPercent = 70;
            // } else {
            // m_loadedPercent += 20;
            // if (m_loadedPercent > 100) {
            // m_loadedPercent = 100;
            // }
            // }

            if (matchFriendFinish) {
                m_max = 101;
                m_loadedPercent = 100;
                setLoadingSyncDataFinish();
            }
        }
    }

    public int getLoadingProgress(int oldProgress) {
        synchronized (this) {
            if (isReset) {
                oldProgress = 0;
                isReset = false;
            }
            if (oldProgress < m_max) {
                oldProgress += 1;
            }
            if (oldProgress < m_loadedPercent) {
                oldProgress = m_loadedPercent;
            }
            if (oldProgress >= 100 && m_loadedPercent < 100) {
                oldProgress = 99;
            }
        }
        return oldProgress;
    }

    private void initReceiver() {
        VLog.e(TAG, "initReceiver");
        IntentFilter filter = new IntentFilter();
//		filter.addAction(FAVOURATEFRAGMENT_LOAD_FINISH);
        filter.addAction(CONTACTFRAGMENT_LOAD_FINISH);
        // filter.addAction(GroupAction.ACTION_SYNCGROUPS_END);
        filter.addAction(AppConstants.FriendShipAction.ACTION_GETMATCHUSERS_END);
        CocoLocalBroadcastUtil.registerLocalBroadCast(receiver, filter);
    }

    public void syncFinish() {
        CocoLocalBroadcastUtil.unregisterLocalBroadCast(receiver);
        manager = null;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {


            String action = intent.getAction();

            VLog.d(TAG, action);
            if (!matchFriendFinish) {
//				matchFriendFinish = SettingHelper
//						.getMatchUserForActivateFinish();
                matchFriendFinish = GetMatchUserManager.isFirstMatched();
                VLog.d(TAG, "isFirstMatched" + matchFriendFinish);
                if (matchFriendFinish) {
                    needShowRetryDialog = false;
                    addLoadedTaskCount();
//					VLog.e("loading", "GETMATCHEDUSER_LOAD_FINISH");
                    UserHelper.setIsMatchEnd();
                }
            }


            if (AppConstants.FriendShipAction.ACTION_GETMATCHUSERS_END.equals(action)) {

                int code = intent.getIntExtra(AppConstants.FriendShipAction.EXTRA_ERRCODE,
                        CocoCode.FriendCode.FAIL);
                VLog.e(TAG, "GETMATCHEDUSER_LOAD_FINISH code = "
                        + code);
                if (CocoCode.FriendCode.OK == code) {
                    needShowRetryDialog = false;
//					matchFriendFinish = true;
                    addLoadedTaskCount();
//					VLog.e("loading", "GETMATCHEDUSER_LOAD_FINISH");
                    UserHelper.setIsMatchEnd();
                } else {
//					needShowRetryDialog = true;
//					CocoLocalBroadcastUtil.sendLocalBroadcast(new Intent(
//							ACTION_GETMATCHEDUSER_RETRY));
                }
            }
        }

    };

    // update to mmkv
    private static SharedPreferences sp;

    public static boolean isLoadingSyncDataFinish() {
        long uid = LoginedUserMgr.getUserId();
        if (uid != ContactUtil.INVALID_ID) {
            if (null == sp) {
                sp = SharedPreferencesManager.getInst().getMMKVSharedPreferences(MAINTAB_LOAD_PROGRESS);
            }
            return sp.getBoolean(uid + "", false);
        }
        return true;
    }

    public static void setLoadingSyncDataFinish() {
        VLog.e(TAG, "setLoadingSyncDataFinish");
        long uid = LoginedUserMgr.getUserId();
        if (uid != ContactUtil.INVALID_ID) {
            if (null == sp) {
                sp = SharedPreferencesManager.getInst().getMMKVSharedPreferences(MAINTAB_LOAD_PROGRESS);
            }
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean(uid + "", true);
            editor.commit();
            CocoLocalBroadcastUtil.sendLocalBroadcast(new Intent(
                    SYNCDATAPROGRESS_END));
        }
    }

    public static void setLoadingSyncDataUnFinished(long uid) {
        if (uid != ContactUtil.INVALID_ID) {
            if (null == sp) {
                sp = SharedPreferencesManager.getInst().getMMKVSharedPreferences(MAINTAB_LOAD_PROGRESS);
            }
            SharedPreferences.Editor editor = sp.edit();
            editor.remove(uid + "");
            editor.commit();
        }
    }

    public boolean isMatchFriendFinish() {
        return matchFriendFinish;
    }

    private boolean isRetryEnd = false;

    public static void setRetryEnd(boolean isRetryEnd) {
        if (null == manager) {
            return;
        }
        if (isRetryEnd) {
            CocoLocalBroadcastUtil.sendLocalBroadcast(new Intent(
                    SYNCDATAPROGRESS_END));
        }
        manager.isRetryEnd = isRetryEnd;
    }

    public static boolean isRetryEnd() {
        if (null == manager) {
            return isLoadingSyncDataFinish();
        }
        return manager.isRetryEnd || isLoadingSyncDataFinish();
    }

    public boolean isNeedShowRetryDialog() {
        return needShowRetryDialog;
    }

    public void setNeedShowRetryDialog(boolean needShowRetryDialog) {
        this.needShowRetryDialog = needShowRetryDialog;
    }

    public static void destroy() {
        synchronized (SyncDataProgressManager.class) {
            manager = null;
        }

    }

}
